import axios from 'axios'
import { send_group_message, } from '@/request/api'



function SendMessage(order, group, msg) {
    this.order = order
    this.group = group
    this.msg = msg
}

var sendMessage = null

// 发送普通群消息
function sendGroup(textList) {
    let newText = textList.map(p => {
        return {
            type: 'Plain',
            text: p
        }
    })
    send_group_message({
        target: sendMessage.group,
        messageChain: newText
    })
}

// 发送图片群消息
function sendGroupImg(imgList) {
    // 消息发送一般不会只是一条，应该格式化messageChain
    let messageChain = imgList.map(p => {
        return {
            type: 'Image',
            url: p.image
        }
    })
    send_group_message({
        target: sendMessage.group,
        messageChain: messageChain
    })
}

function testAIDrawing() {
    let token = ''
    if (!sessionStorage.getItem('accessToken')) {
        console.log('没有可以使用的accessToken')
        return
    }
    else {
        token = JSON.parse(sessionStorage.getItem('accessToken'))
    }
    // 分析格式化之后的消息；msgFormat，0：指令，1：style，2：text
    // style支持：油画、水彩画、卡通、粉笔画、儿童画、蜡笔画
    let styles = ['油画','水彩画','卡通','粉笔画','儿童画','蜡笔画']
    let text = ''
    if (sendMessage.msg.length==1) {
        sendGroup([sendMessage.order.reply])
        return
    }
    else if (sendMessage.msg.length==2) {
        if (!styles.includes(sendMessage.msg[1])) {
            sendGroup(['未知的风格词汇\n',sendMessage.order.reply])
            return
        }
    }
    else if (sendMessage.msg.length>2) {
        text = sendMessage.msg.slice(2).join(' ')
    }
    
    axios.post('https://wenxin.baidu.com/moduleApi/portal/api/rest/1.0/ernievilg/v1/txt2img',{
        access_token: token,
        text: text,
        style: sendMessage.msg[1]
    }).then(res => {
        if (!error(res.data)) return
        let taskId = res.data.data.taskId
        getAIImg(token, taskId)

        // 判断imgUrls字段是否为空来暂停定时器
        let time = setInterval(() => {
            getAIImg(token, taskId,time)
        }, 5000);
    })
        
}
async function getAIImg(token, taskId, time) {
    axios.post('https://wenxin.baidu.com/moduleApi/portal/api/rest/1.0/ernievilg/v1/getImg',{
        access_token: token,
        taskId: taskId
    }).then(res => {
        if (!error(res.data)) return
        if (res.data.data.imgUrls&&res.data.data.imgUrls.length>0) {
            sendGroupImg(res.data.data.imgUrls)
            clearInterval(time)
        }
    })
}

// 文心接口错误状态收集
function error(res) {
    if (res.code != 0) {
        sendGroup([res.msg])
        return false
    }
    return true
}

export function formatFunc(order, msgFormat, group) {
    sendMessage = new SendMessage(order, group, msgFormat)
    eval(order.func+'()')
}